﻿using AppDataStruct;
using ComForm;
using ComForm.Auxiliary;
using ComUIControl;
using EECMISWS;
using KCommon;
using KeyboardArg;
using KWindow.KPageCore;
using LogLib;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Windows.Forms;

namespace YSLPages
{
    public partial class PageFillPersonInfo : PageControlBase
    {


        private PreApplyInfo _appInfo = null;

        private SFZInfo _sfz = new SFZInfo();

        private TextBox textBoxSFZHM = null;

        private TextBox textBoxPYM = null;

        private TextBox textBoxPYX = null;

        private TextBox textBoxZWX = null;

        private TextBox textBoxZWM = null;

        private TextBox textBoxXB = null;

        private TextBox textBoxHKSZD = null;

        private TextBox textBoxContactNumber = null;

        private TextBox textBoxEmergencyPhoneNumber = null;

        private TextBox textBoxZY = null;

        private CodeMapService _mapService = null;
        private bool _bInited = false;

        public PageFillPersonInfo()
        {
            InitializeComponent();
            SetProcessBase(ProcessFillPersonInfo.Instance);
        }

        private void GetControls()
        {
            textBoxContactNumber = GetControl<TextBox>("textBoxContactNumber") as TextBox;
            textBoxEmergencyPhoneNumber = GetControl<TextBox>("textBoxEmergencyPhoneNumber") as TextBox;
            textBoxSFZHM = GetControl<TextBox>("textBoxSFZHM") as TextBox;
            textBoxPYM = GetControl<TextBox>("textBoxPYM") as TextBox;
            textBoxPYX = GetControl<TextBox>("textBoxPYX") as TextBox;
            textBoxZWX = GetControl<TextBox>("textBoxZWX") as TextBox;
            textBoxZWM = GetControl<TextBox>("textBoxZWM") as TextBox;
            textBoxXB = GetControl<TextBox>("textBoxXB") as TextBox;
            textBoxHKSZD = GetControl<TextBox>("textBoxHKSZD") as TextBox;
            textBoxZY = GetControl<TextBox>("textBoxZY") as TextBox;
            if (textBoxZWX != null)
            {
                textBoxZWX.TextChanged += OnZWXTextChanged;
            }
            if (textBoxZWM != null)
            {
                textBoxZWM.TextChanged += OnZWMTextChanged;
            }
        }

        private void InitCodeMapService()
        {
            _mapService = CodeMapService.Instance;
            if (!_mapService.Inited)
            {
                _mapService.LoadConfig();
            }
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            InitKeyboards();
            base.InitCtrls();
            GetControls();
            InitCodeMapService();
        }

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            _bInited = false;
            _appInfo = Process.GetValue<PreApplyInfo>("PreApplyInfo");

            textBoxSFZHM.Enabled = true;
            _sfz = Process.GetValue<SFZInfo>("SFZInfo");

            ////////////////
            //GLJ 2022/12/14     TextBox测试数据
            ////////////////
            //_appInfo = new PreApplyInfo();
            //CodeMap code1 = new CodeMap();
            //CodeMap code3 = new CodeMap();
            //CodeMap code4 = new CodeMap();
            //CodeMap code5 = new CodeMap();
            //CodeMap code6 = new CodeMap();
            //_appInfo.ZWX = "张";
            //_appInfo.ZWX = "三";
            //_appInfo.CSRQ = "1999-03-05";
            //code1.Value = "汉族";
            //code3.Value = "男";
            //code4.Value = "广东省";
            //code5.Value = "教师";
            //code6.Value = "广东省";
            //_appInfo.MZ = code1;
            //_appInfo.XB = code3;
            //_appInfo.CSD = code4;
            //_appInfo.ZY = code5;
            //_appInfo.HKSZD = code6;
            //_appInfo.JJLXDH = "13511111111";
            //_appInfo.JJLXR = "李四";
            //_appInfo.LXDH = "13540252051";
            //_appInfo.SFZH = "4322341199903052312";
            //_appInfo.XCRX = null;

            //_sfz = new SFZInfo();
            //_sfz.Name = "测试";
            //_sfz.ExpiryDate = "2033-11-11";
            //_sfz.IsManualInputNumberVerify = true;
            //_sfz.BirthDate = "1985-10-31";
            //_sfz.Sex = "男";
            //_sfz.Sex_Code = "1";
            //_sfz.Nation = "汉";
            //_sfz.Nation_Code = "01";
            //_sfz.SFZH = "440782198510310019";

            //Process.SetValue("SFZInfo", _sfz);
            //Process.SetValue("PreApplyInfo", _appInfo);
            ///////////////////////////////////////////////////////////

            InitTextBoxs();
            _bInited = true;
        }

        private void TextBox()
        {
            SFZInfo info = new SFZInfo();
            textBoxSFZHM.Text = info.SFZH;
        }

        protected void InitTextBoxs()
        {
            try
            {
                if (_appInfo == null)
                {
                    Log.WriteAsync("申请查询的信息为空");
                    return;
                }
                if (_sfz == null)
                {
                    Log.WriteAsync("身份证信息为空");
                    return;
                }

                Log.WriteAsync($"apply info:{KCommon.JsonHandler.ConvertToJsonString<PreApplyInfo>(_appInfo)}");
                Log.WriteAsync($"sfz info:{KCommon.JsonHandler.ConvertToJsonString<SFZInfo>(_sfz)}");
                Log.WriteAsync($"TextBoxs数量：{TextBoxs.Count}");
                Type type = _appInfo.GetType();
                string FieldName = "";
                foreach (TextBox tb in TextBoxs)
                {
                    Log.WriteAsync("TextBoxName:" + tb.Name);
                    if (!TextBoxBindings.ContainsKey(tb.Name))
                    {
                        continue;
                    }
                    FieldName = TextBoxBindings[tb.Name].Key;
                    Log.WriteAsync("TextBox:" + TextBoxBindings[tb.Name].Key);
                    System.Reflection.PropertyInfo propertyInfo = type.GetProperty(FieldName);
                    if (propertyInfo != null)
                    {
                        if (propertyInfo.PropertyType == typeof(CodeMap))
                        {
                            CodeMap cm = (CodeMap)propertyInfo.GetValue(_appInfo, null);
                            tb.Text = cm.Value; //给对应属性赋值
                            textMapService[FieldName] = cm.Value;
                            Log.WriteAsync("CodeMap,Code:" + cm.Code + ",Value:" + cm.Value);
                        }
                        else
                        {
                            tb.Text = (string)propertyInfo.GetValue(_appInfo, null); //给对应属性赋值
                        }
                        Log.WriteAsync("文本框" + tb.Name + "：" + tb.Text);
                    }
                    else
                    {
                        Log.WriteAsync("找不到名称为[" + FieldName + "]属性.");
                    }
                }
                Log.WriteAsync("身份证号码：" + _appInfo.SFZH);
                //Log.WriteAsync("(本地)身份证号码：" + _sfz.SFZH);
                //if (string.IsNullOrEmpty(_appInfo.SFZH))
                //{
                //    textBoxSFZHM.Enabled = true;
                //}
                //else
                //{
                //    textBoxSFZHM.Enabled = false;
                //}
                string xing = "";
                string ming = "";
                if (string.IsNullOrEmpty(_appInfo.ZWXM))
                {
                    if (!string.IsNullOrEmpty(_sfz.Name))
                    {
                        int ret = _sfz.GetXingAndMing(_sfz.Name,out xing, out ming);
                        if (ret != 0)
                        {
                            Log.WriteAsync($"解析中文姓名失败1:{ret}");
                            return;
                        }
                    }
                }
                else
                {
                    int ret = _sfz.GetXingAndMing(_appInfo.ZWXM, out xing, out ming);
                    if (ret != 0)
                    {
                        Log.WriteAsync($"解析中文姓名失败2:{ret}");
                        return;
                    }
                }

                if (IsMainPage)
                {
                    MingToPinYin();
                    XingToPinYin();
                }
                else
                {
                    textBoxPYX.Text = Process.GetValue<string>("PYX");
                    textBoxPYM.Text = Process.GetValue<string>("PYM");
                }

                textBoxZWX.Text = xing;
                textBoxZWM.Text = ming;
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
            }

        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            Log.WriteAsync("开始更新数据");
            // 更新关键字/键值索引字典
            textMapService.UpdateMapDic();
            if (_appInfo == null)
                return;
            Type type = _appInfo.GetType();
            string FieldName = "";
            string FieldValue = "";
            foreach (TextBox tb in TextBoxs)
            {
                if (!TextBoxBindings.ContainsKey(tb.Name))
                {
                    continue;
                }
                FieldName = TextBoxBindings[tb.Name].Key;
                FieldValue = tb.Text.Trim();
                System.Reflection.PropertyInfo propertyInfo = type.GetProperty(FieldName);
                if (propertyInfo != null)
                {

                    if (propertyInfo.PropertyType == typeof(CodeMap))
                    {
                        if (propertyInfo.Name != "HKSZD")
                        {
                            string code = _mapService.FindCode(FieldName, FieldValue);
                            propertyInfo.SetValue(_appInfo, new CodeMap(code, FieldValue), null);
                            Log.WriteAsync($"（{propertyInfo.Name}） CodeMap code:{code},value:{FieldValue}");
                        }
                    }
                    else
                    {
                        propertyInfo.SetValue(_appInfo, FieldValue, null); //给对应属性赋值
                        Log.WriteAsync($"（{propertyInfo.Name}） value:{FieldValue}");
                    }
                }
                else
                {
                    Log.WriteAsync("找不到名称为[" + FieldName + "]属性.");
                }
            }
            Log.WriteAsync($"hkszd code 1:{_appInfo.HKSZD.Code},value:{_appInfo.HKSZD.Value}");
            if (string.IsNullOrEmpty(_appInfo.HKSZD.Code))
            {
                if (textMapService.TextMap.ContainsKey("HKSZD"))
                {
                    _appInfo.HKSZD.Code = textMapService["HKSZD"];
                }
            }
            Log.WriteAsync($"hkszd code 2:{_appInfo.HKSZD.Code},value:{_appInfo.HKSZD.Value}");

            Process.SetValue("PreApplyInfo", _appInfo);
            //base.Update();
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            _appInfo = null;
            _sfz = null;
            foreach (TextBox tb in TextBoxs)
            {
                tb.Text = "";
            }
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {
            base.Close();
        }

        public override void StartWork()
        {
            base.StartWork();
            //textBoxSFZHM.Select();
            //textBoxSFZHM.Focus();
            CheckFillingIsCompleted();
        }

        public override void StopWork()
        {
            base.StopWork();
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            Log.WriteAsync("倒计时结束，未能完善个人信息，中止申请流程.");
            base.OnCountdownCompleted(sender, e);
        }

        protected override void btnBack_Click(object sender, EventArgs e)
        {
            StopCountdown();
            base.btnBack_Click(sender, e);
        }

        protected override void btnNext_Click(object sender, EventArgs e)
        {
            Log.WriteAsync("点击了下一步");
            if (!CheckAllInfoIsFilling())
                return;
            UpdateData();
            StopCountdown();
            base.btnNext_Click(sender, e);
        }

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            StopCountdown();
            base.btnCancel_Click(sender, e);
        }

        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case (int)MessageType.WM_COPYDATA:
                    OnKeyBoardMsgReceived(m);
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }

        protected bool CheckAllInfoIsFilling()
        {
            Type type = _appInfo.GetType();
            foreach (TextBox tb in TextBoxs)
            {
                if (!TextBoxBindings.ContainsKey(tb.Name))
                {
                    continue;
                }

                KeyBoardArgs args = TextBoxBindings[tb.Name];
                

                if (!string.IsNullOrEmpty(tb.Text))
                {
                    System.Reflection.PropertyInfo propertyInfo = type.GetProperty(args.Key);
                    if (propertyInfo != null && propertyInfo.PropertyType == typeof(CodeMap))
                    {
                        if (propertyInfo.Name != "HKSZD")
                        {
                            string code = _mapService.FindCode(args.Key, tb.Text.Trim());
                            if (string.IsNullOrEmpty(code))
                            {
                                Log.WriteAsync($"（{propertyInfo.Name}） CodeMap code:{code},value:{tb.Text.Trim()}");

                                string msg = string.Format("选项[{0}]代码为空，请重新选择。", args.Title);
                                MsgBox.Show(msg);
                                return false;
                            }
                        }
                    }

                    continue;
                }

                if (args.NotNull)
                {
                    string msg = string.Format("选项[{0}]不能为空，请填写。", args.Title);
                    MsgBox.Show(msg);
                    return false;
                }
            }
            if (textBoxContactNumber.Text == textBoxEmergencyPhoneNumber.Text)
            {
                MsgBox.Show("本人联系电话和紧急联系电话不能相同.");
                return false;
            }
            return true;
        }

        /// <summary>
        /// 复姓字
        /// </summary>
        private static string[] MultiName = new string[]
        {
            "欧阳","太史","端木","上官","司马","东方","独孤","南宫","万俟","闻人","夏侯","诸葛","尉迟","公羊","赫连","澹台",
            "皇甫","宗政","濮阳","公冶","太叔","申屠","公孙","慕容","仲孙","钟离","长孙","宇文","城池","司徒","鲜于","司空",
            "闾丘","子车","亓官","司寇","巫马","公西","颛孙","壤驷","公良","漆雕","乐正","宰父","谷梁","拓跋","夹谷","轩辕",
            "令狐","段干","百里","呼延","东郭","南门","羊舌","微生","公户","公玉","公仪","梁丘","公仲","公上","公门","公山",
            "公坚","左丘","公伯","西门","公祖","第五","公乘","贯丘","公皙","南荣","东里","东宫","仲长","子书","子桑","即墨",
            "达奚","褚师"
        };

        private string GetSelecedMultiPinYin(ChinesePinyin AllPinYins)
        {
            List<string> listSels = AllPinYins.PinYins;
            string ch = AllPinYins.ChineseWord.ToString();
            int sel = 0;
            if (listSels == null || listSels.Count == 0)
            {
                return "";
            }
            else if (listSels.Count <= 3)
            {
                FormSelectPinYin form = new FormSelectPinYin(ch, listSels);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    sel = form.SelectIndex;
                }
            }
            else if (listSels.Count <= 6)
            {
                FormSelectPinYinG form = new FormSelectPinYinG(ch, listSels);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    sel = form.SelectIndex;
                }
            }
            return listSels[sel];
        }

        private string PinYinWordsSeparator = "";

        private MultiPinYinSelMode SelMode = MultiPinYinSelMode.ManualSel;
        private void XingToPinYin()
        {
            string zwx = textBoxZWX.Text.Trim();
            if (string.IsNullOrEmpty(zwx) || zwx.Length == 0)
            {
                return;
            }
            string pinYin = KPinYinConverter.ConvertToPinYin(zwx, PinYinWordsSeparator, SelMode, GetSelecedMultiPinYin);
            textBoxPYX.Text = pinYin;
            Process.SetValue("PYX", pinYin);
        }

        private void MingToPinYin()
        {
            string zwm = textBoxZWM.Text.Trim();
            if (string.IsNullOrEmpty(zwm) || zwm.Length == 0)
            {
                return;
            }
            string pinYin = KPinYinConverter.ConvertToPinYin(zwm, PinYinWordsSeparator, SelMode, GetSelecedMultiPinYin);
            textBoxPYM.Text = pinYin;
            Process.SetValue("PYM", pinYin);
        }

        private void OnZWXTextChanged(object sender, EventArgs e)
        {
            if (_bInited)
            {
                XingToPinYin();
            }
        }

        private void OnZWMTextChanged(object sender, EventArgs e)
        {
            if (_bInited)
            {
                MingToPinYin();
            }
        }
    }
}
